import React, { useState, useEffect } from 'react';
import './App.css';

const App = () => {
  const [currentPage, setCurrentPage] = useState('todo');
  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState('');
  const [editingId, setEditingId] = useState(null);
  const [editingText, setEditingText] = useState('');
  const [searchText, setSearchText] = useState('');
  const [currentFilterType, setCurrentFilterType] = useState('all');
  let todoIdCounter = 1;

  useEffect(() => {
    console.log('React 应用已加载！');
  }, []);

  const addTodo = () => {
    if (newTodo.trim()) {
      setTodos(prev => [...prev, {
        id: todoIdCounter++,
        text: newTodo.trim(),
        completed: false
      }]);
      setNewTodo('');
    }
  };

  const toggleTodo = (id) => {
    setTodos(prev => 
      prev.map(todo => 
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };

  const removeTodo = (id) => {
    setTodos(prev => prev.filter(todo => todo.id !== id));
  };

  const clearAll = () => {
    setTodos([]);
  };

  const startEdit = (id, text) => {
    setEditingId(id);
    setEditingText(text);
  };

  const saveEdit = (id) => {
    if (editingText.trim()) {
      setTodos(prev => 
        prev.map(todo => 
          todo.id === id ? { ...todo, text: editingText.trim() } : todo
        )
      );
    }
    cancelEdit();
  };

  const cancelEdit = () => {
    setEditingId(null);
    setEditingText('');
  };

  const handleEditKeyPress = (e, id) => {
    if (e.key === 'Enter') {
      saveEdit(id);
    } else if (e.key === 'Escape') {
      cancelEdit();
    }
  };

  // 过滤后的todos
  const filteredTodos = todos.filter(todo => {
    // 按状态过滤
    if (currentFilterType === 'completed' && !todo.completed) return false;
    if (currentFilterType === 'pending' && todo.completed) return false;
    
    // 按搜索文本过滤
    if (searchText.trim() && !todo.text.toLowerCase().includes(searchText.toLowerCase())) {
      return false;
    }
    
    return true;
  });

  const completedCount = todos.filter(todo => todo.completed).length;
  const remainingCount = todos.length - completedCount;

  return (
    <div className="react-app">
      <nav className="nav">
        <button 
          className={`nav-btn ${currentPage === 'todo' ? 'active' : ''}`}
          onClick={() => setCurrentPage('todo')}
        >
          Todo List
        </button>
        <button 
          className={`nav-btn ${currentPage === 'blank' ? 'active' : ''}`}
          onClick={() => setCurrentPage('blank')}
        >
          空白页面
        </button>
      </nav>

      {/* Todo List 页面 */}
      {currentPage === 'todo' && (
        <div className="page">
          <h1>📝 React Todo List</h1>
          <div className="add-todo">
            <input 
              value={newTodo}
              onChange={(e) => setNewTodo(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && addTodo()}
              placeholder="输入新的待办事项..."
              className="todo-input"
            />
            <button onClick={addTodo} className="btn">添加</button>
            <button onClick={clearAll} className="btn btn-danger">清空全部</button>
          </div>
          
          <div className="search-filter">
            <input 
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              placeholder="搜索待办事项..."
              className="todo-input"
            />
            <div className="filter-buttons">
              <button 
                className={`filter-btn ${currentFilterType === 'all' ? 'active' : ''}`}
                onClick={() => setCurrentFilterType('all')}
              >
                全部
              </button>
              <button 
                className={`filter-btn ${currentFilterType === 'completed' ? 'active' : ''}`}
                onClick={() => setCurrentFilterType('completed')}
              >
                已完成
              </button>
              <button 
                className={`filter-btn ${currentFilterType === 'pending' ? 'active' : ''}`}
                onClick={() => setCurrentFilterType('pending')}
              >
                未完成
              </button>
            </div>
          </div>
          
          <div className="todo-list">
            {filteredTodos.length === 0 ? (
              <div className="empty-message">
                {searchText.trim() ? '没有找到匹配的待办事项' : '暂无待办事项'}
              </div>
            ) : (
              filteredTodos.map(todo => (
              <div key={todo.id} className={`todo-item ${todo.completed ? 'completed' : ''}`}>
                {editingId === todo.id ? (
                  <>
                    <input 
                      type="text"
                      value={editingText}
                      onChange={(e) => setEditingText(e.target.value)}
                      onKeyPress={(e) => handleEditKeyPress(e, todo.id)}
                      onBlur={() => saveEdit(todo.id)}
                      className="todo-edit-input"
                      autoFocus
                    />
                    <div className="todo-actions">
                      <button onClick={() => saveEdit(todo.id)} className="btn">保存</button>
                      <button onClick={cancelEdit} className="btn">取消</button>
                    </div>
                  </>
                ) : (
                  <>
                    <span 
                      className="todo-text" 
                      onClick={() => toggleTodo(todo.id)}
                    >
                      {todo.text}
                    </span>
                    <div className="todo-actions">
                      <button 
                        onClick={() => startEdit(todo.id, todo.text)}
                        className="btn"
                      >
                        编辑
                      </button>
                      <button 
                        onClick={() => removeTodo(todo.id)}
                        className="btn btn-danger"
                      >
                        删除
                      </button>
                    </div>
                  </>
                )}
              </div>
            ))
            )}
          </div>
          
          <p className="todo-stats">
            总计: {todos.length} | 已完成: {completedCount} | 未完成: {remainingCount}
          </p>
        </div>
      )}

      {/* 空白页面 */}
      {currentPage === 'blank' && (
        <div className="page">
          <div className="blank-content">
            <h2>🎨 React 空白页面</h2>
            <p>这是一个空白页面，你可以在这里练习 React Hooks 开发。</p>
            <p className="hint">提示：编辑 react-app/src/App.jsx 文件来修改这个页面</p>
            
            {/* 在这里添加你的 React 代码 */}
            
          </div>
        </div>
      )}
    </div>
  );
};

export default App;
